﻿Imports System.Web
Imports System.Web.Services
Imports System.Data.Common
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration
Imports Newtonsoft.Json
Imports FY.YinXinSDK
Imports FY.YinXinSDK.RecMsg
Imports FY.YinXinSDK.ReplyMsg
Imports TjLog
Public Class YiXinHandler
    Implements System.Web.IHttpHandler
    Public Shared Function ToJson(obj As Object) As String
        Return JsonConvert.SerializeObject(obj)
    End Function

    Public Shared Function JsonTo(Of T)(json As String) As T
        Return JsonConvert.DeserializeObject(Of T)(json)
    End Function
    Private Shared Sub YinXin_OnReceiveMsgEvent(Plat_Code As String, xml As String, dict As Dictionary(Of String, String))
        If dict.ContainsKey("Event") Then
            Dim Streventkey As String = If(dict.ContainsKey("EventKey"), dict("EventKey"), "")
        Else
            If dict.ContainsKey("MsgId") Then
                Dim StrMsgId As String = dict("MsgId")
            End If
        End If
    End Sub

    Private Shared lockobj As Object
    Shared Sub New()
        Dim yixin_db As Database = EnterpriseLibraryContainer.Current.GetInstance(Of Database)("fyyixin")

        lockobj = New Object()

        AddHandler YinXin.OnReceivePlatMsgEvent, AddressOf YinXin_OnReceiveMsgEvent

        YinXin.RegisterEventHandler(Of EventAttendMsg)(Function(msg As EventAttendMsg, plat_code As String)
                                                           Try
                                                               Return ServiceProcess.Process(plat_code, "AttendEvent", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                           Catch ex As Exception
                                                               Return ReplyEmptyMsg.Instance
                                                           End Try
                                                       End Function)

        YinXin.RegisterEventHandler(Of EventUnattendMsg)(Function(msg As EventUnattendMsg, plat_code As String)
                                                             Try
                                                                 Return ServiceProcess.Process(plat_code, "UnattendEvent", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                             Catch ex As Exception
                                                                 Return ReplyEmptyMsg.Instance
                                                             End Try
                                                         End Function)

        YinXin.RegisterEventHandler(Of EventClickMsg)(Function(msg As EventClickMsg, plat_code As String)
                                                          Try
                                                              Return ServiceProcess.Process(plat_code, "ClickMenuEvent", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                          Catch ex As Exception
                                                              Return ReplyEmptyMsg.Instance
                                                          End Try
                                                      End Function)
        YinXin.RegisterEventHandler(Of EventLocationMsg)(Function(msg As EventLocationMsg, plat_code As String)
                                                             Try
                                                                 Return ServiceProcess.Process(plat_code, "LocationEvent", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                             Catch ex As Exception
                                                                 Return ReplyEmptyMsg.Instance
                                                             End Try
                                                         End Function)
        YinXin.RegisterEventHandler(Of EventFansScanMsg)(Function(msg As EventFansScanMsg, plat_code As String)
                                                             Try
                                                                 Return ServiceProcess.Process(plat_code, "FansScanEvent", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                             Catch ex As Exception
                                                                 Return ReplyEmptyMsg.Instance
                                                             End Try
                                                         End Function)
        YinXin.RegisterEventHandler(Of EventUserScanMsg)(Function(msg As EventUserScanMsg, plat_code As String)
                                                             Try
                                                                 Return ServiceProcess.Process(plat_code, "UserScanEvent", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                             Catch ex As Exception
                                                                 Return ReplyEmptyMsg.Instance
                                                             End Try
                                                         End Function)

        YinXin.RegisterMsgHandler(Of RecTextMsg)(Function(msg As RecTextMsg, plat_code As String)
                                                     Try
                                                         Return ServiceProcess.Process(plat_code, "TextMsg", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                     Catch ex As Exception
                                                         Return ReplyEmptyMsg.Instance
                                                     End Try
                                                 End Function)
        YinXin.RegisterMsgHandler(Of RecImageMsg)(Function(msg As RecImageMsg, plat_code As String)

                                                      Try
                                                          Return ServiceProcess.Process(plat_code, "ImageMsg", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                      Catch ex As Exception

                                                          Return ReplyEmptyMsg.Instance
                                                      End Try

                                                  End Function)

        YinXin.RegisterMsgHandler(Of RecLocationMsg)(Function(msg As RecLocationMsg, plat_code As String)

                                                         Try
                                                             Return ServiceProcess.Process(plat_code, "LocationMsg", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                         Catch ex As Exception
                                                             Return ReplyEmptyMsg.Instance
                                                         End Try
                                                     End Function)
        YinXin.RegisterMsgHandler(Of RecVideoMsg)(Function(msg As RecVideoMsg, plat_code As String)
                                                      Try
                                                          Return ServiceProcess.Process(plat_code, "VideoMsg", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                      Catch ex As Exception
                                                          Return ReplyEmptyMsg.Instance
                                                      End Try

                                                  End Function)
        YinXin.RegisterMsgHandler(Of RecVoiceMsg)(Function(msg As RecVoiceMsg, plat_code As String)
                                                      Try
                                                          Return ServiceProcess.Process(plat_code, "VoiceMsg", "<msg><![CDATA[" & ToJson(msg) & "]]></msg><platcode><![CDATA[" & plat_code & "]]></platcode>")
                                                      Catch ex As Exception

                                                          Return ReplyEmptyMsg.Instance
                                                      End Try
                                                  End Function)
    End Sub

    
    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        context.Response.ContentType = "text/plain"
        Dim plat_code As String = If(context.Request.QueryString("plat_code"), String.Empty)
        Try
            If String.IsNullOrEmpty(plat_code) Then
                '不符合调用逻辑，必须带有此平台的唯一识别编码
                Log.ErrorLog("微信调用我方服务器端URL中不含有plat_code参数，不符合规则！请重新登录微信公众平台设置和微信通讯的url串！", "0000", "19", "验证微信调用我方服务url中是否包含plat_code参数", "verifyplat_code")
                Log.FileLog.Error("验证微信调用我方服务url中是否包含plat_code参数:微信调用我方服务器端URL中不含有plat_code参数，不符合规则！请重新登录微信公众平台设置和微信通讯的url串！")
                '请求错误，直接返回，不再执行以下逻辑
                Return
            Else
                Dim arg_9D_0 As String = If(context.Request.QueryString("state"), String.Empty)
                Dim code As String = If(context.Request.QueryString("code"), String.Empty)
                Dim callback As String = If(context.Request.QueryString("callback"), String.Empty)
                Dim signature As String = If(context.Request.QueryString("signature"), String.Empty)
                Dim timestamp As String = If(context.Request.QueryString("timestamp"), String.Empty)
                Dim nonce As String = If(context.Request.QueryString("nonce"), String.Empty)
                Dim echostr As String = If(context.Request.QueryString("echostr"), String.Empty)
                ReflectStruct.ReadConfigDLL(plat_code)
                If Not String.IsNullOrEmpty(code) AndAlso Not String.IsNullOrEmpty(plat_code) Then
                    Dim credent As WebCredential = YinXin.GetWebAccessToken(plat_code, code)
                    Dim CredentJsonStr As String = JsonConvert.SerializeObject(credent)
                    If Not String.IsNullOrEmpty(callback) Then
                        context.Response.Write(callback + "(" + CredentJsonStr + ")")
                    Else
                        context.Response.Write(CredentJsonStr)
                    End If
                    Log.FileLog.Info(CredentJsonStr)
                Else
                    If YinXin.CheckSignature(signature, timestamp, nonce, YinXin.GetToken(plat_code)) Then
                        If Not String.IsNullOrEmpty(echostr) Then
                            Log.InfoLog("", plat_code, "-1-1", "与微信公众平台服务器验证通信成功", "verify", "我方服务器", "微信公众平台服务器")
                            Log.FileLog.Info("与微信公众平台服务器验证通信成功")
                            context.Response.Write(echostr)
                        Else
                            Dim replyMsg As String = YinXin.ReplyMsgProcess(plat_code).GetXML()
                            Log.InfoLog(replyMsg, plat_code, "-2-2", "回复消息给用户", "reply")
                            Log.FileLog.Info("回复消息" + replyMsg)
                            context.Response.Write(replyMsg)
                        End If
                    Else
                        Log.ErrorLog("", plat_code, "-1-1", "与微信公众平台服务器验证通信失败", "verify", "我方服务器", "微信公众平台服务器")
                        Log.FileLog.Error("与微信公众平台服务器验证通信失败")
                        context.Response.Write("与微信服务器验证通信失败！")
                    End If
                End If
            End If
        Catch ex As Exception
            Log.ErrorLog(ex.Message)
            Log.FileLog.Error(ex.Message)
        End Try
    End Sub

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class